﻿using System;
using System.Collections.Generic;

namespace CommonUtils
{
    public class ChinaUtil
    {
        public static Dictionary<string, string> ZoneCodeNameDict = new Dictionary<string, string>();

        static ChinaUtil()
        {
            var text = ResourceUtil.GetTextFromCommon("行政编号-行政区域.txt");
            text.GetLines().Each(line =>
            {
                var cells = line.SplitByComma();
                ZoneCodeNameDict.Add(cells[0], cells[1]);
            });
        }

        public static string GetIdentityIndex(string sex = null)
        {
            var index = RandomUtil.Get(1000);
            if (sex == "男")
                index = (index >> 1 << 1) + 1;
            if (sex == "女")
                index = index >> 1 << 1;
            return index.ToString("000");
        }

        public static string GetIdentitySex(string number)
        {
            if (int.Parse(number.Substring(0, 17)) % 2 == 0)
                return "女";
            else
                return "男";
        }

        public static string GetIdentityVerify(string number)
        {
            int[] values = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
            int sum = 0;
            for (int index = 0; index < 17; index++)
                sum += int.Parse(number[index].ToString()) * values[index];
            switch (sum % 11)
            {
                case 0: return "1";
                case 1: return "0";
                case 2: return "X";
                case 3: return "9";
                case 4: return "8";
                case 5: return "7";
                case 6: return "6";
                case 7: return "5";
                case 8: return "4";
                case 9: return "3";
                case 10: return "2";
                default: return "ERROR";
            }
        }

        public static string GetIdentity(string zoneCode, DateTime birthDate, string sex = null)
        {
            var idNum = zoneCode + birthDate.ToString("yyyyMMdd") + GetIdentityIndex(sex);
            var verify = GetIdentityVerify(idNum);
            return idNum + verify;
        }

        public static string GetRandomIdentity()
        => GetIdentity(ZoneCodeNameDict.Keys.ToArray<string>()[RandomUtil.Get(ZoneCodeNameDict.Count)], TimeUtil.RandomDate());
    }
}
